package com.jzr.board.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File
import java.math.RoundingMode
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException
import java.text.DecimalFormat

object CommonUtil {


    fun getBaseUrl(): String? {
        return "http://" + PreferUtil.getInstance().serviceIp
            .toString() + ":" + PreferUtil.getInstance().serverPort
    }


    fun getWifiInfo(context: Context): String? {
        val wifiManager =
            context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        return wifiInfo.ssid
    }


    /***
     * 获取本机IP地址
     */
    fun getIP(): String? {
        try {
            val en =
                NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf = en.nextElement()
                val enumIpAddr =
                    intf.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                        return inetAddress.getHostAddress().toString()
                    }
                }
            }
        } catch (ex: SocketException) {
            ex.printStackTrace()
        }
        return null
    }


    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content
     * 传入的字符串
     * @param frontNum
     * 保留前面字符的位数
     * @param endNum
     * 保留后面字符的位数
     * @return 带星号的字符串
     */
    fun replaceString2Star(
        content: String?,
        frontNum: Int,
        endNum: Int
    ): String? {
        if (content == null || content.trim { it <= ' ' }.isEmpty()) return content
        val len = content.length
        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0) return content
        if (frontNum + endNum >= len) return content
        val endIndex = len - endNum
        val cardChar = content.toCharArray()
        for (j in frontNum until endIndex) {
            cardChar[j] = '*'
        }
        return String(cardChar)
    }



    fun replaceNameX(realname:String?): String? {
        var realname1: String? = null
        val r = realname?.toCharArray()
        if (r?.size == 1) {
            realname1 = realname
        }
        if (r?.size == 2) {
            realname1 = realname.replaceFirst(realname.substring(1).toRegex(), "*")
        }
        if (r?.size!! > 2) {
            realname1 = realname.replaceFirst(realname.substring(1, r?.size - 1).toRegex(), "*")
        }
        return realname1

    }


    /**
     * 安装apk
     */
    fun installApk(context: Context?, file: File): Boolean {
        if (!file.exists()) {
            return false
        }
        val intent = Intent(Intent.ACTION_VIEW)
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val contentUri: Uri = FileProvider.getUriForFile(
                context!!,
                "com.jzr.board.fileprovider",
                file
            )
            //设置 intent 目标应用类型和传递的数据，这句要放在查询之前
            intent.setDataAndType(
                contentUri,
                "application/vnd.android.package-archive"
            )
            //            Logger.e("uri : " + contentUri.toString());
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        } else {
            intent.setDataAndType(
                Uri.fromFile(file),
                "application/vnd.android.package-archive"
            )
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context?.startActivity(intent)
        return true
    }


    fun getNoMoreThanTwoDigits(number: Double): String {
        val format = DecimalFormat("0.##")
        //未保留小数的舍弃规则，RoundingMode.FLOOR表示直接舍弃。
        format.roundingMode = RoundingMode.FLOOR
        return format.format(number)
    }


}